package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Configuration//配置类,全局配置
@RestControllerAdvice //返回值要求是json风格,对所有controller的增强
@Slf4j
public class ExceptionCatch {

    @ExceptionHandler(Exception.class)//异常处理器
    public ResponseResult exception(Exception e){
      log.error("服务器出现异常,===>{}",e);

      return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"服务器出现异常,请稍候重试");
    }

    @ExceptionHandler(CustomException.class)//先处理自定义异常,再处理全局异常,从小到大处理
    public ResponseResult customHandle(Exception e){

        log.error("自定义异常,===>{}",e);
        CustomException customException=(CustomException) e;

        return ResponseResult.errorResult(customException.getAppHttpCodeEnum());//把自定义的异常信息取出来,返回给前端
    }


    //事务问题,return指正常结束,后面的不会执行,事务无法回滚

    /**
     * 参数校验
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    //@ResponseBody
    public ResponseResult handleValidationException(MethodArgumentNotValidException ex) {
        log.error("MethodArgumentNotValidException ex:{}", ex);
        ex.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, ex.getBindingResult().getFieldError().getDefaultMessage());
    }
}
